/**
 * _ooOoo_
 * o8888888o
 * 88" . "88
 * (| -_- |)
 * O\ = /O
 * ____/`---'\____
 * .   ' \\| |// `.
 * / \\||| : |||// \
 * / _||||| -:- |||||- \
 * | | \\\ - /// | |
 * | \_| ''\---/'' | |
 * \ .-\__ `-` ___/-. /
 * ___`. .' /--.--\ `. . __
 * ."" '< `.___\_<|>_/___.' >'"".
 * | | : `- \`.;`\ _ /`;.`/ - ` : | |
 * \ \ `-. \_ __\ /__ _/ .-` / /
 * ======`-.____`-.___\_____/___.-`____.-'======
 * `=---='
 * <p>
 * .............................................
 * 佛祖保佑             永无BUG
 */

package com.handpay.zztong.hp.base.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.handpay.framework.ClientEngine;
import com.handpay.framework.HttpEngine;
import com.handpay.framework.HttpSFTConnector;
import com.handpay.framework.LuaTableUtil;
import com.handpay.framework.NetEngineListener;
import com.handpay.framework.SecureManager;
import com.handpay.framework.swiper.ApiSwiperFactory;
import com.handpay.framework.swiper.IPersonalSwiper;
import com.handpay.framework.swiper.ISwiperListener;
import com.handpay.framework.swiper.SwiperDetectService;
import com.handpay.framework.swiper.SwiperMode;
import com.handpay.framework.swiper.SwiperModel;
import com.handpay.framework.swiper.ic.IICSelectApplicationCallback;
import com.handpay.framework.swiper.landi.AipSharedPreferences;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.framework.utils.Heart;
import com.handpay.framework.utils.MyAsyncTask;
import com.handpay.framework.utils.UserCheckTimeout;
import com.handpay.framework.utils.ViewServer;
import com.handpay.zztong.hp.CameraCardPhotoActivity;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.ZZTApplication;
import com.handpay.zztong.hp.accountcenter.model.Bank;
import com.handpay.zztong.hp.accountcenter.model.BankList;
import com.handpay.zztong.hp.accountcenter.model.BankProvince;
import com.handpay.zztong.hp.accountcenter.model.BankProvinceList;
import com.handpay.zztong.hp.accountcenter.model.SubBankBean;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.bean.Address;
import com.handpay.zztong.hp.bean.BankArea;
import com.handpay.zztong.hp.bean.ResponseBean;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.config.ZZTConstant;
import com.handpay.zztong.hp.download.activity.DownloadApkActivity;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.login.activity.FindPwdActivity;
import com.handpay.zztong.hp.login.activity.LoginActivity;
import com.handpay.zztong.hp.login.activity.RegisterActivity;
import com.handpay.zztong.hp.login.activity.WelcomeActivity;
import com.handpay.zztong.hp.login.model.VerifyVersionBean;
import com.handpay.zztong.hp.main.activity.MainActivity;
import com.handpay.zztong.hp.other.activity.ShowHtmlActivity;
import com.handpay.zztong.hp.permission.PermissionRequestCode;
import com.handpay.zztong.hp.protocol.ATProtocolConstant;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.protocol.CardProtocolKey;
import com.handpay.zztong.hp.protocol.UCProtocolKey;
import com.handpay.zztong.hp.qualification.model.BankAreaBean;
import com.handpay.zztong.hp.swiper.SwiperUtils;
import com.handpay.zztong.hp.swiper.activity.ConnectSwiperActivity;
import com.handpay.zztong.hp.swiper.model.SwiperBluetoothDeviceSelectInfo;
import com.handpay.zztong.hp.swiper.model.SwiperDeviceSelectInfo;
import com.handpay.zztong.hp.swiper.model.SwiperStatusBean;
import com.handpay.zztong.hp.trans.activity.VPOSActivity;
import com.handpay.zztong.hp.ui.AbTitleBar;
import com.handpay.zztong.hp.ui.ZZTShowDialog;
import com.handpay.zztong.hp.utils.AccountUtils;
import com.handpay.zztong.hp.utils.BitmapZipUtils;
import com.umeng.analytics.MobclickAgent;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.apache.http.HttpStatus;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Vector;
import java.util.zip.CRC32;

import se.krka.kahlua.vm.LuaTable;

import static com.handpay.zztong.hp.permission.PermissionRequestCode.REQUEST_CODE_FINDLOCATION;

public class ZZTongActivity extends BaseActivity implements ISwiperListener, View.OnClickListener, PermissionListener {
    private final String TAG = ZZTongActivity.class.getSimpleName();
    private int mEncRetryCount = 0;
    // 加密失败只重试一次。
    private int MAXRETRIES = 1;
    public final static int REQUEST_CONNECT_DEVICE = 100; // 定义查询格尔蓝牙设备
    public final static int REQUEST_APPLYPR_CODE = 102; // 申购
    public final static int REQUEST_APPLYPR_CODE_TIP = 104; // 申购
    public final static int REQUEST_REDEEM_CODE = 103; // 赎回功能刷新界面
    public final static int REQUEST_CONNECT_DEVICE1 = REQUEST_CONNECT_DEVICE + 1; // 定义查询新大陆蓝牙设备
    // 新增联迪M36
    public final static int REQUEST_CONNECT_M36DEVICE = 0X1004;
    public final static int REQUEST_CONNECT_M35DEVICE = 0X1001;
    public final static int REQUEST_CONNECT_ME31DEVICE = 0X1002;
    // 新增 ME368
    public final static int REQUEST_CONNECT_ME368DEVICE = 0X1003;
    // 新增 ME368
    public final static int REQUEST_CONNECT_VOICE = 0X1005;
    // 新增ME15
    public final static int REQUEST_CONNECT_ME15DEVICE = 0X1006;

    // 新增BBPOS M188
    public final static int REQUEST_CONNECT_M188DEVICE = 0X1007;
    // 新增艾创I21B
    public final static int REQUEST_CONNECT_I21BDEVICE = 0X1008;

    private final long CREATE_TIME = SystemClock.elapsedRealtime();
    public static final String ACTION = "action";
    public static final String ACTION_FROM = "action_from";
    public static final String ForResult = "forresult";
    public boolean flag_isShow_updatePWD = true;//该变量主要控制密码过期提示只提示一次即可
    public boolean forresult = false; // 是否返回结果
    protected byte mAction = Action_INVALID;// 执行协议类型
    public static final byte Action_ReadCSN = 0,// 读取CSN
            Action_Register = 1,// 开通，加密PIN
            Action_GetCSNStatus = 2,// 刷卡器状态查询
            Action_Login = 3,// 使用
            Action_Account = 4,// 账户管理
            Action_AddAccount = 5,// 绑卡，加密PIN
            Action_DelAccount = 6,// 删卡
            Action_QueryBills = 7,// 交易查询
            Action_Transfer1 = 8,// 转账1（选卡确认金额）
            Action_Transfer2 = 9,// 转账2（发起转账请求）
            Action_BalanceEnquiry = 10,// 余额查询
            Action_ModifyPassword1 = 11,// 修改密码1（修改密码界面）
            Action_ModifyPassword2 = 12,// 修改密码2（发起修改密码请求）
            Action_SameTransfer1 = 13,// 同名转账1（选卡确认金额）
            Action_SameTransfer2 = 14,// 同名转账2（发起转账请求）
            Action_SuperTransfer = 15,// 超级转账
            Action_CreditCardRepay = 16,// 信用卡还款
            Action_Phone = 17,// 手机网页充值
            Action_Qb = 18,// Q币网页充值
            Action_Game = 19,// 游戏网页
            Action_MARKET = 20, //  分销系统
            Action_SuperUniTrans = 21,//银联转账
            Action_INVALID = -1; // 非法action
    public static final byte Action_FROM_UNI_TRANS = 1, Action_FROM_CREDIT = 2; // 非法action

    public static final String POLL_TIME = "POLL_TIME"; // 组件间隔时间
    public static final String VerifyVersionOK = "VerifyVersionOK"; // 版本检测是否成功
    public static final String Do_VerifyVersion = "zztVerifyVersion.do",// 9.1.
    // 版本检测
    Do_ActivateSession = "activateSession.do",// 9.2. Session激活
            Do_GetCSNStatus = "zztGetCSNStatus.do",// 10.1. 刷卡器状态查询
            Do_Register = "zztAccountRegister.do",// 10.2. 账账通开通
            Do_Login = "zztLogin.do",// 10.3. 账账通使用
            Do_GetAccounts = "zztGetAccounts.do",// 10.4. 获取签约银行账户
            Do_AddAccount = "zztAddAccount.do",// 10.5. 添加签约银行账户
            Do_DelAccount = "zztDelAccount.do",// 10.6. 删除签约银行账户
            Do_QueryFee = "zztQueryFee.do",// 11.1. 查询转账手续费
            Do_BalanceEnquiry = "zztBalanceEnquiry.do",// 11.2. 余额查询
            Do_BalanceEnquiry20 = "zztBalanceEnquiry20.do",// 11.2. 余额查询
            Do_QueryBills = "zztQueryBills.do",// 11.3. 交易查询
            Do_Transfer = "zztTransfer.do",// 11.4. 账账通转账
            Do_Transfer20 = "zztTransfer20.do",// 11.4. 账账通转账
            DO_AccountTransfer = "zztAccountTransfer.do",// 11.6. 账账通帐户转账
            DO_AccountTransfer20 = "zztAccountTransfer20.do",// 11.6. 账账通帐户转账

    Do_ModifyPassword = "zztModifyCSNPwd.do", // 10.7 账账通CSN密码修改
            Do_SubatmQueryFee = "subatmQueryFee.do", // 12.1. 查询快速转账手续费
            Do_SubatmTransfer = "subatmTransfer.do", // 12.3. 快速转账
            Do_UploadSig = "uploadSign.do", // 12.2 保存电子签名
            Do_BindSwiper = "zztBindSwiper.do",// 10.19 绑定刷卡器
            Do_GetSwiperStatus = "zztGetSwiperStatus.do", // 10.20查询刷卡器状态
            Do_UploadCheckInfo = "zztUCInfo.do", // 13.1.上传/检查审核基本信息
            Do_UploadPicInfo = "zztUploadPicInfo.do", // 13.2.上传审核图片信息
            Do_AccountLogin = "zztAccountLogin.do",// 10.9. 账账通用户使用
            Do_GetBanks = "zztGetBanks.do", // 14.5.请求银行列表
    // Do_SearchSubBanks = "zztSearchBanks.do", //14.6.查询支行银行列表
    Do_SendPhoneCode = "zztSendPhoneCode.do", // 14.1发送手机验证码
            DO_zztGetLimit = "zztGetLimit.do",// 10.17 交易限额查询
            DO_zztAccountExit = "zztAccountExit.do",// 10.21. 账账通账户退出
            DO_zztGetMerchantInfo = "zztGetMerchantInfo.do",// 13.5. 获取当前账户详情
            DO_zztSendPhoneCode = "zztSendPhoneCode.do",// 14.1. 发送手机短信认证码
            DO_zztCheckPhoneNum = "zztCheckPhoneNum.do",// 10.14. 验证手机号
            DO_zztModifyPhoneNum = "zztModifyPhoneNum.do",// 10.13. 修改账户手机号
            DO_zztModifyCardNum = "zztModifyCardNum.do",// 10.15. 修改收款账户信息
            DO_zztGetAuditInfo = "zztGetAuditInfo.do",// 13.3. 获取当前审核信息
            Do_QueryAccountBills = "zztQueryAccountBills.do",// 11.5. 账户交易查询
            Do_ModifyResetPassword = "zztModifyAccountPwd.do", // 10.12
    // 修改/重置账户密码
    Do_QueryHXFourElements = "queryHXFourElements.do", // VPOSActivity 25.1
    // 韩鑫四要素，查询请求
    Do_AddHXFourElements = "addHXFourElements.do", // 25.2 保留本次认证结果
            Do_ZztBankList = "zztBankList.do", // 获取收款行主行列表
            Do_ZztBankProvinceList = "zztBankProvinceList.do", // 获取收款行省份列表
            Do_ZztBankAreaList = "zztBankAreaList.do", // 15.3. 获取收款行地区列表
            Do_ZztSubBankList = "zztSubBankList.do", // 15.4. 获取收款行支行列表
            Do_GetLowestAccountTransferAmount = "zztGetLowestAccountTransferAmount.do", Do_GetLowestWithdrawMoney = "zztGetLowestWithdrawMoney.do", // 提现金额最低阀值
            Do_ZztNewVerifyVersion = "zztNewVerifyVersion.do",// 9.2新版本检测
            Do_ZztVersionDesc = "zztVersionDesc.do", // 9.4版本说明
            DO_GetAvailableWithdrawMoney = "getAvailableWithdrawMoney.do", // 查询用户当前可提现金额
            Do_ZztRateList = "zztRateList.do", // 9.4版本说明
            Do_ZztGFFundIndex = "zztGFFundIndex.do",// 请求广发首页信息
            Do_ZztGFReturnHistory = "zztGFReturnHistory.do",// 广发查询收益历史记录
            Do_ZztGFPurchaseHistory = "zztGFPurchaseHistory.do",// 广发查询理财历史记录
            Do_ZztPurchaseRecordDetail = "zztPurchaseRecordDetail.do",// 广发查询理财详情
            Do_ZztGFPaymentInfo = "zztGFPaymentInfo.do", // 基金申购信息
            Do_ZztGFPayment = "zztGFPayment.do", // 申请申购
            Do_ZztRedemptionInfo = "zztRedemptionInfo.do", // 17.3.5赎回申请操作信息
            Do_ZztRedemption = "zztRedemption.do",//
            Do_ZztAutoPaymentFinancingProduct = "zztAutoPaymentFinancingProduct.do",//
            Do_GetUserNotices = "getUserNotices.do", // 当前是否需要自动购买广发“慧存钱”
            Do_GetBannersByChannel = "getBannersByChannel.do",//
            Do_zztMerchantCollect = "zztMerchantCollect.do", Do_GetPhotoSwitch = "getPhotoSwitch.do",// 获取
            Do_GetBusinessControlSwitch = "getBusinessControlSwitch.do",// 获取消费卡拍照、刷卡收款转出卡四要素等功能的业务标记开关。
            Do_ZztPurchaseCardCollectInfo = "zztPurchaseCardCollectInfo.do",// 11.11.//
    // 收款交易消费卡信息采集
    Do_getMerchantSwitch = "getMerchantSwitch.do",// 获取t0资质拍照开关
            Do_getMerchantPicPreview = "getMerchantPicPreview.do",// 获取资质预览照片
            Do_uploadMerchantPic = "uploadMerchantPic.do",// //提交资质图片
            Do_deleteMerchantPicById = "deleteMerchantPicById.do",// 删除资质图片
            Do_CheckSwipeCardFourElements = "checkSwipeCardFourElements.do", //
            Do_WalletAccountTransfer = "zztWalletAccountTransfer.do",// 通过选择支付宝钱包或者微信支付的方式从用户手机扫码扣款完成商户收款功能
            Do_GetAreaTradeValue = "getAreaTradeValue.do",// 获取地理位置
            Do_zztRevokeTransaction = "zztRevokeTransaction.do",// 撤销交易
            Do_NewQueryAccountBills = "zztQueryTransactionBills.do",//新交易流水
            Do_QueryAppeals = "zztQueryAppeal.do",//交易申诉查询
            Do_TransactionAppeal = "zztTransactionAppeal.do",//收款交易申诉
            DO_GetAvailableTradeType = "getAvailableTradeType.do",//获取支付方式
            Do_QrCodeTransferSwitch = "zztQrCodeTransferSwitch.do",//获取微信正扫开关
            Do_QrCodeTransfer = "zztNewQrCodeTransfer.do",//获取商户二维码
            Do_QrCodeTransferClose = "zztQrCodeTransferClose.do",//关闭微信正扫开关
            Do_QueryQrCodeTransferResult = "zztQueryQrCodeTransferResult.do",//获取微信正扫支付结果
            Do_GetMarketOrderDetailByOrderId = "getMarketOrderDetailByOrderId.do",//31.	分销系统订单查询
            DO_MarketAccountTransfer = "zztMarketAccountTransfer.do",// 32.分销系统刷卡收款
            Do_QueryCertNoExpiryDate = "zztQueryCertNoExpiryDate.do",//根据登录商户编号查询该商户的身份证有效期信息。
            Do_UpdateMerchantCertInfo = "zztUpdateMerchantCertInfo.do",//上传身份证补件信息功能。
            Do_tGetSupplyAuditInfo = "zztGetSupplyAuditInfo.do",//获取当前登录商户的补件审核信息。
            Do_GetLoginVerificationCode = "getLoginVerifiCode.do",//获取验证码
            Do_RecordUserVisit = "zztRecordUserVisit.do",//统计接入外部业务的访问信息。
            Do_CustomComponentList = "getCustomComponentList.do",//获取指定客户端需要展示的功能组件列表，展示区域包括：首页、基本应用、增值应用。
            Do_GetHistoryBankCardList = "getHistoryBankCardList.do",//获取登录用户无卡支付交易成功的历史卡列表。;
            Do_DeleteHistoryBankCardList = "deleteHistoryBankCardList.do",//用户清除无卡支付历史卡记录。;
            Do_GetMerchantTypeList = "getNewMerchantTypeList.do",//获取无卡支付商户类型列表。
            Do_GetSignTransImage = "zztGetSignTransImage.do"; // 12.2 根据交易流水号获取该笔交易的签购单图片。


    public static final String ACCOUNT = "account";
    public static final String FRAGMENTFLAG = "fragmentFlag";
    public static final String PHONE = "phone";
    public static final String STATUS = "status";
    public static final String FAIL_DESCRIPTION = "failDescription";
    public static final String UPDATEURL = "updateurl";
    public static final String VERSION = "version";
    public static final String DESCRIPTION = "description";
    public static final String FORCEDUPDATE = "forcedUpdate";
    public static final String NOTICEINFO = "noticInfo";
    public static final String PAYTYPE = "paytype";
    public static int screenWidth = -1;
    public static int screenHeight = -1;
    public static String PAGESIZE = "30";
    public static String newBankFlag = "1";
    public static String pageSize = "0";
    private SharedPreferences sharedPreferences;

    public static boolean isUploadComposeSusses = false;
    // 新版账账通优化
    public AbTitleBar myActionBar;
    // 每个activity在onStart状态监听，在onStop状态取消监听。
    private HeadsetPlugReceiver mHeadsetPlugReceiver = new HeadsetPlugReceiver();

    public RequestQueue requestQueue;

    public UserCheckTimeout chekUserTimeout;
    //该变量主要用于数据被回收  ，页面的onSaveInstanceState方式设置的数据key
    public static final String key_saveInstanceState = "key_account";

    protected void swiperWarning(String msg) {
        stopAdpu();
        try {
            this.closeProgressDialog();
            // 可以搞个函数，让每个具体类去实现，决定要不要显示出错对话框
            HPLog.i(TAG, "swiperWarning:" + getLocalClassName());
            if (getLocalClassName().contains("VPOSActivity")) {
                this.showAlertDialog(this, getString(R.string.tip), msg, false, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });
            }
        } catch (Exception e) {
            HPLog.e(TAG, "", e);
        }

    }

    private void csnWarning(String content) {
        if (this.getClass() == ConnectSwiperActivity.class) {
            DialogInterface.OnClickListener click = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    goBack();
                    dialog.dismiss();
                }
            };
            this.showAlertDialog(this, getString(R.string.tip), content, true, click);
        } else {
            this.showAlertDialog(this, getString(R.string.tip), content, true, null);
        }

    }

    public void stopAdpu() {
        // 应该在这里调用停止刷卡器的操作。

        new MyAsyncTask<Void, Void, Void>() {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // ZZTongActivity.this.showProgressDialog(ZZTongActivity.this,
                // getString(R.string.wait));
            }

            @Override
            protected Void doInBackground(Void... params) {
                ApiSwiperFactory.getInstance().stopOperation();
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                ZZTongActivity.this.closeProgressDialog();
            }

            @Override
            protected void onCancelled(Void result) {
                super.onCancelled();
                ZZTongActivity.this.closeProgressDialog();
            }
        }.execute();

    }

    /**
     * 数据置空
     */
    public void toNull() {
        // account = null;
        // pin = null;
        // encAmount = null;
        // track2 = null;
        // track3 = null;
    }

    /**
     * 下面三个函数，都是选择卡应用的接口。
     */
    @Override
    public void showSelectICApp(ArrayList<String> cardTypes, IICSelectApplicationCallback selectApplicationCallback) {

    }

    @Override
    public void showNoAvailableApp(Runnable r) {

    }

    @Override
    public void closeSelectICApp() {

    }

    public class HeadsetPlugReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // 监听耳麦的状态
            if (action.equals(SwiperDetectService.SWIPER_CONNECT_STATE_ACTION)) {
                boolean state = intent.getBooleanExtra(SwiperDetectService.SWIPER_CONNECT_STATE_KEY, false);
                IPersonalSwiper.SwiperType swiperType;
                int ordinal = intent.getIntExtra(SwiperDetectService.SWIPER_TYPE_KEY, -1);
                if (-1 == ordinal) {
                    return;
                }
                swiperType = IPersonalSwiper.SwiperType.values()[ordinal];
                if (state) {
                    // 监听连接音频或蓝牙连接成功，不自动发出Status_connect，只有用户选择的时候，才发出Plug in消息
                    // onSwiperStatus(ISwiperListener.Status_Connect,ISwiperListener.Swiper_Plug_In);
                } else {
                    HPLog.i(TAG, "收到刷卡器断开处理");
                    if (swiperType == ApiSwiperFactory.getInstance().getSwiperType()) {
                        HPLog.i(TAG, "IPersonalSwiper.SwiperType:do onDeviceDisconnect");
                        onDeviceDisconnect(swiperType);
                    }
                }
                HPLog.i(TAG, "HeadsetPlugReceiver CHANNEL:" + ZZTConfig.UPDATE_CHANNEL + "state: " + state + " swiperType:" + swiperType);
                Bundle results = getResultExtras(true);
                results.putBoolean(SwiperDetectService.SWIPER_RESULT_KEY, true);
            }

        }

        private void onDeviceDisconnect(IPersonalSwiper.SwiperType swiperType) {
            // Toast.makeText(ZZTongActivity.this,
            // getString(R.string.toast_device_disconnect),
            // Toast.LENGTH_SHORT).show();
            onSwiperStatus(ISwiperListener.Status_Connect, ISwiperListener.Swiper_Plug_Off, null, false);
            ApiSwiperFactory.getInstance().clearSwiper(swiperType);
            // AipSharedPreferences.getInstance(ZZTongActivity.this).setDeviceInfo(null);
            // AipSharedPreferences.getInstance(ZZTongActivity.this).setLastSelectDevice(null);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        HPLog.i(TAG, "onConfigurationChanged");
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (isListenerVoice()) {
            registerHeadsetPlugReceiver();
        }
    }

    @Override
    protected void onPause() {
        // umeng add
        MobclickAgent.onPause(this);
        super.onPause();
    }

    @Override
    protected void onResume() {
        ZZTApplication.ZZTApp.addActivityStatus(this, true);
        MobclickAgent.onResume(this);
        super.onResume();
        if (ZZTConfig.isActive && !(this instanceof WelcomeActivity) && !(this instanceof DownloadApkActivity) && !(this instanceof CameraCardPhotoActivity) && !(this instanceof VPOSActivity)) {
            // app 从后台唤醒，进入前台
//            doVerifyVersion(this);
        }
        ZZTConfig.isActive = false;
    }

    @Override
    protected void onStop() {
        ZZTApplication.ZZTApp.addActivityStatus(this, false);
        boolean alived = ZZTApplication.ZZTApp.isAllActivityAlive();
        if (!alived) {
            ZZTConfig.isActive = true;
        }
        super.onStop();
        if (isListenerVoice()) {
            unregisterReceiver();
        }
    }

    /**
     * 注册耳机孔监听
     */
    private void registerHeadsetPlugReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(SwiperDetectService.SWIPER_CONNECT_STATE_ACTION);
        registerReceiver(mHeadsetPlugReceiver, intentFilter);
    }

    private void unregisterReceiver() {
        unregisterReceiver(mHeadsetPlugReceiver);
    }

    /**
     * 这个函数，暂时不需要去调用 刷卡器相关，是整个应用的生命周期都需要的。 不需要自己强制去卸载掉刷卡器。但是一旦内存低，我们应该怎么处理呢？这些还是
     * 占着资源，容易被杀死。
     */
    public void clearSwiper() {
        ApiSwiperFactory.getInstance().exit();
        unregisterReceiver();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        HPLog.i("onNewIntent", ((Object) this).getClass().getSimpleName());
        super.onNewIntent(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Heart.initialize(this);
        HPLog.d("decivesinfo", "density:" + Heart.density + "|displayWidthPixels:" + Heart.displayWidthPixels + "|displayHeightPixels:" + Heart.displayHeightPixels + "|dpi:" + Heart.densityDpi);
        //所有页面需要取得用户数据从onSaveInstanceState中
        if (savedInstanceState != null) {
            HPLog.i(HPLog.TAG_RESULT, "data from savedInstanceState...");
            AccountUtils.Account account = (AccountUtils.Account) savedInstanceState.getSerializable(key_saveInstanceState);
            if (account != null) {
                HPLog.i(HPLog.TAG_RESULT, account.toString());
                AccountUtils.saveAccount(this, account.getAccount(), account.getPhone(), account.getStatus(), account.getFailDes(), account.getMerchantCode(), account.getUserId());
            }
        }
        if (TextUtils.isEmpty(AccountUtils.getAccountName(this))) {
            // 除了这四个activity以外，其他的activity如果没有账户名，全都退出。
            if (!(this instanceof WelcomeActivity || this instanceof LoginActivity || this instanceof RegisterActivity || this instanceof FindPwdActivity || this instanceof ShowHtmlActivity || this instanceof DownloadApkActivity)) {

                // 程序被杀死会出现这种情况。
                exitAccount();
                return;
            }
        }
        chekUserTimeout = new UserCheckTimeout(this);
        screenWidth = getResources().getDisplayMetrics().widthPixels;
        screenHeight = getResources().getDisplayMetrics().heightPixels;
        if (isListenerVoice()) {
            ApiSwiperFactory.getInstance().registerListener(this);
        }

        myActionBar = (AbTitleBar) this.findViewById(R.id.top_actionbar);
        if (isShownTopBar()) {
            if (myActionBar != null) {
                myActionBar.ininTitleBar(this);
                myActionBar.refreshActionBar(getActivityActionBar());
                initActionBarAndTabHeight();
                if (!isVisiableTopBar()) {
                    myActionBar.setVisibility(View.GONE);
                }
            } else {
                throw new RuntimeException("please use top_bar.xml");
            }
        }

        if (ZZTConfig.ENV.PRINTLOG) {
            ViewServer.get(this).addWindow(this);
        }
        sharedPreferences = this.getSharedPreferences("data",  Context.MODE_PRIVATE);
        ZZTApplication.ZZTApp = (ZZTApplication) this.getApplication();
    }

    /**
     * @return
     */
    protected boolean isVisiableTopBar() {
        return true;
    }

    /**
     * 初始化ActionBar 和 Tab 的高度
     */
    public void initActionBarAndTabHeight() {
        TypedValue tv = new TypedValue();
        if (this.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
            int actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, this.getResources().getDisplayMetrics());
            android.view.ViewGroup.LayoutParams params = myActionBar.getLayoutParams();
            params.height = actionBarHeight;
            myActionBar.setLayoutParams(params);
        }
    }

    // 设置标题 按钮 事件
    public ActionBar getActivityActionBar() {
        return null;
    }

//    public enum TABPOS {
//        LEFT, CENTER, RIGHT
//    }

//    private TABPOS mSelectedTabIndex = TABPOS.LEFT;

//    // 0 表示左边，1表示中间，2表示右边
//    protected void hightTab(TABPOS selected) {
//        attachTab(selected);
//        switch (selected) {
//            case LEFT: {
//                this.findViewById(R.id.tab_account).setSelected(true);
//                break;
//            }
//            case CENTER: {
//                this.findViewById(R.id.tab_transfer).setSelected(true);
//                break;
//            }
//            case RIGHT: {
//                this.findViewById(R.id.tab_function).setSelected(true);
//                break;
//            }
//        }
//    }

//    protected void attachTab(TABPOS selected) {
//        mSelectedTabIndex = selected;
//    }

    protected boolean isShownTopBar() {
        return true;
    }

    protected boolean isShownTabs() {
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isListenerVoice()) {
            ApiSwiperFactory.getInstance().unRegisterListener(this);
        }
        if (ZZTConfig.ENV.PRINTLOG) {
            ViewServer.get(this).removeWindow(this);
        }
    }

    public boolean isListenerVoice() {
        return true;
    }

    /**
     * 跳转到和刷卡器交互界面
     *
     * @param activity
     * @param action   修改Action类型为int 原来的为byte
     */
    public void startActivityForResult(ZZTongActivity activity, Class<?> cls, Hashtable<String, Object> params, int action) {
        Intent intent = getIntent(activity, cls, params);
        intent.putExtra(ForResult, true);
        activity.startActivityForResult(intent, action);
    }

    public void startActivity(ZZTongActivity activity, Class<?> cls, Hashtable<String, Object> params) {
        Intent intent = getIntent(activity, cls, params);
        intent.putExtra(ForResult, false);
        activity.startActivity(intent);
    }

    public Intent getIntent(ZZTongActivity activity, Class<?> cls, Hashtable<String, Object> params) {
        Intent intent = new Intent(activity, cls);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        if (params != null && !params.isEmpty()) {
            Iterator<Entry<String, Object>> p = params.entrySet().iterator();
            while (p.hasNext()) {
                Map.Entry<String, Object> entry = p.next();
                String name = entry.getKey();
                Object value = entry.getValue();
                if (value instanceof Boolean) {
                    intent.putExtra(name, (Boolean) value);
                } else if (value instanceof String) {
                    intent.putExtra(name, (String) value);
                } else if (value instanceof Double) {
                    intent.putExtra(name, (Double) value);
                } else if (value instanceof Integer) {
                    intent.putExtra(name, (Integer) value);
                } else if (value instanceof Byte) {
                    intent.putExtra(name, (Byte) value);
                } else if (value instanceof Serializable) {
                    intent.putExtra(name, (Serializable) value);
                }
            }
        }
        return intent;
    }


    /**
     * 版本验证，并显示等待对话框
     */
    public boolean doVerifyVersion(ZZTongActivity activity) {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put("version", ClientEngine.VERSION);
        params.put("platform", ClientEngine.MOBILETYPE);
        params.put("channel", ZZTConfig.UPDATE_CHANNEL);
        return doJsonPost(true, activity, Do_ZztNewVerifyVersion, VerifyVersionBean.class, params, false);
    }

    /**
     * @param resp 后台返回的数据
     * @return true表示遇到登录超时的情况
     */
    public boolean dealWithLoginTimeOut(Hashtable<String, Object> resp) {
        byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
        if (null != data) {
            LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
            if (null != luaTable) {
                String em = (String) luaTable.rawget("errMessage");
                if (!TextUtils.isEmpty(em)) {
                    Object responseCode = luaTable.rawget("responseCode");
                    OnClickListener exitlogin = new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            exitAccount();
                            dialog.dismiss();
                        }
                    };
                    final OnClickListener exit_app = new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            exitapp();
                            dialog.dismiss();
                        }
                    };
                    if (responseCode instanceof Double) {
                        if (99 == (Double) responseCode) {
                            this.showAlertDialog(this, null, em, false, exitlogin);
                            return true;
                        } else if (999 == (Double) responseCode) {
                            showAlertDialog(this, getString(R.string.offline_notify_txt), em, false, getString(R.string.tv_exit), exit_app, getString(R.string.tv_relogin), exitlogin);
                            return true;
                        }
                    } else {
                        if ("99".equals(responseCode)) {
                            this.showAlertDialog(this, null, em, false, exitlogin);
                            return true;
                        } else if (responseCode.equals("999")) {
                            showAlertDialog(this, getString(R.string.offline_notify_txt), em, false, getString(R.string.tv_exit), exit_app, getString(R.string.tv_relogin), exitlogin);
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    public void exitAccount() {
        HPLog.i("ZZTongActivity", this.getClass().getName() + " no account! go to Login");
        AccountUtils.ClearAccount(this.getApplicationContext());
        SwiperUtils.setSwiperStatus("", "");
        SwiperUtils.cleanSwiperData();
        ZZTApplication.getApp().exitApp();
        if (chekUserTimeout != null) {
            chekUserTimeout.clearTime();
        }
        Intent Login = new Intent(this, LoginActivity.class);
        this.startActivity(Login);
        this.finish();
    }

    public void exitapp() {
        AccountUtils.ClearAccount(this);
        SwiperUtils.setSwiperStatus("", "");
        SwiperUtils.cleanSwiperData();
        ZZTApplication.getApp().exitApp();
        this.finish();
    }

    @Override
    public boolean netJsonResponse(String action, ResponseBean resp, boolean showAlert, OnClickListener on) {
        closeProgressDialog();
        if (!TextUtils.isEmpty(resp.responseCode)) {
            if (action.equals(Do_GetSwiperStatus)) {//解决首次注册链接刷卡器 csn不在合法列表直接退出应用程序处理：不关闭当前Activity
                if (resp.getResponseCode() != null && resp.getErrMessage() != null && showAlert) {
                    showAlertDialog(this, getString(R.string.tip), resp.getErrMessage(), false, new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    return true;
                }
            } else {
                OnClickListener exitlogin = new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        exitAccount();
                        dialog.dismiss();
                    }
                };
                final OnClickListener exit_app = new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        exitapp();
                        dialog.dismiss();
                    }
                };
                if ("99".equals(resp.getResponseCode())) {

                    showAlertDialog(this, getString(R.string.prompt), resp.getErrMessage(), false, exitlogin);
                    return true;
                } else if (resp.getResponseCode().equals("999")) {

                    showAlertDialog(this, getString(R.string.offline_notify_txt), resp.getErrMessage(), false, getString(R.string.tv_exit), exit_app, getString(R.string.tv_relogin), exitlogin);
                    return true;
                }
                if (resp.getResponseCode() != null && resp.getErrMessage() != null && showAlert) {
                    if (on != null) {
                        showAlertDialog(this, getString(R.string.tip), resp.getErrMessage(), false, on);
                    } else {
                        showAlertDialog(this, getString(R.string.tip), resp.getErrMessage());
                    }
                    return true;
                }
            }

        }
        return dealJsonResponse(action, resp);
    }

    @Override
    public boolean netResponse(String action, Hashtable<String, Object> resp, boolean showAlert, OnClickListener on) {
        int respCode = (Integer) resp.get(HttpEngine.Key_RespCode);
        String errMsg = (String) resp.get(HttpEngine.Key_RespErrMsg);
        if (respCode == HttpStatus.SC_REQUEST_TIMEOUT) {
            this.showAlertDialog(this, getString(R.string.hint_timer_out), errMsg, false, on);
            cancelVolleyRequest(action);
            return true;
        } else if (respCode == HttpStatus.SC_NOT_FOUND) {
            this.showAlertDialog(this, getString(R.string.hint_conn_err), errMsg, false, on);
            cancelVolleyRequest(action);
            return true;
        } else if (respCode == HttpStatus.SC_SERVICE_UNAVAILABLE) {
            this.showAlertDialog(this, getString(R.string.hint_server_error), errMsg, false, on);
            cancelVolleyRequest(action);
            return true;
        } else if (respCode == HttpStatus.SC_UNAUTHORIZED) {
            this.showAlertDialog(this, getString(R.string.hint_author_error), errMsg, false, on);
            cancelVolleyRequest(action);
            return true;
        }
        if (dealWithLoginTimeOut(resp)) {
            return true;
        }
        // 目前主要针对版本管理，类似“找不到对应的程序版本信息” 做的处理
        byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
        LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
        if (luaTable == null) {
            return true;
        }
        int responseCode = -1;
        responseCode = CommonUtils.objectToInt(luaTable.rawget("responseCode"));
        if (responseCode != 0) {
            String errMessage = CommonUtils.objectToString(luaTable.rawget("errMessage"));
            if (errMessage != null && showAlert) {
                showAlertDialog(this, getString(R.string.tip), errMessage);
                return true;
            }
        }
        closeProgressDialog();
        return dealResponse(action, resp);
    }

    /**
     * @param action
     * @param resp
     * @return true 已处理完毕 false 未处理完毕
     */
    public boolean dealJsonResponse(String action, ResponseBean resp) {
        if (action.equals(Do_ZztNewVerifyVersion)) {
            int responseCode;
            try {
                if (resp == null) {
                    return false;
                }
                VerifyVersionBean bean = (VerifyVersionBean) resp;
                // 降级交易
                String dgTrade = bean.getDgTrade();
                if (null != dgTrade) {
                    if ("0".equals(dgTrade)) {
                        ZZTConfig.DW_TRADE = false;
                    } else if ("1".equals(dgTrade)) {
                        ZZTConfig.DW_TRADE = true;
                    }
                }

                responseCode = CommonUtils.objectToInt(bean.getResponseCode());
                if (responseCode == 0) {
                    ClientEngine.getInstance().saveGlobal(ZZTongActivity.VerifyVersionOK, true);// 只用于登陆时，是否做了版本检测
                    ClientEngine.getInstance().saveGlobal(POLL_TIME, bean.getPollTime());
                    String version = bean.getVersion();
                    String url = bean.getUrl();
                    String description = bean.getDescription();
                    String forcedUpdate = bean.getForcedUpdate();
                    // 保存此数据 在HpAboutActivity中用
                    ClientEngine.getInstance().saveGlobal(VERSION, version);
                    ClientEngine.getInstance().saveGlobal(DESCRIPTION, description);
                    ClientEngine.getInstance().saveGlobal(UPDATEURL, url);
                    ClientEngine.getInstance().saveGlobal(FORCEDUPDATE, forcedUpdate);
                    if (TextUtils.isEmpty(url) && TextUtils.isEmpty(description)) {
                        return true;
                    } else {
                        description = description.replace("&", "\n");
                    }
                    String title = getString(R.string.updatetitle, version);
                    String message = description;
                    int result = version.compareTo(ClientEngine.VERSION);
                    if ("0".equals(forcedUpdate) && result > 0) {
                        String mVersion = null;
                        mVersion = sharedPreferences.getString("VERSION", "");
                        HPLog.i("ZZTongActivity", "mVersion:" + mVersion);
                        if (!TextUtils.isEmpty(mVersion) && version.equals(mVersion)) {
                            return true;
                        } else {
                            isforcedCheckVersion(ZZTongActivity.this, title, message, url, version);
                        }
                    } else {
                        checkVersion(this, title, message, url);
                    }
                    return false;
                }
            } catch (Exception e) {
                HPLog.e(TAG, "", e);
                return true;
            }
        } else if (action.equals(Do_GetSwiperStatus)) {
            SwiperStatusBean swiperStatusBean = (SwiperStatusBean) resp;
            SwiperUtils.setSwiperStatus(swiperStatusBean.getStatus(), swiperStatusBean.getMessage());
            // 重新检查刷卡器
            if (SwiperUtils.isAccountSwiper()) {
                goToVPos();
            } else {
                if (SwiperUtils.canBind()) {
                    goToVPos();
                    return false;
                } else {
                    showAlertDialog(this, getString(R.string.tip), swiperStatusBean.getMessage(), true, new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            SwiperUtils.cleanSwiperData();
                            dialog.dismiss();
                        }
                    });
                    return true;
                }
            }
        } else if (Do_BindSwiper.equals(action)) {
            // 绑定刷卡器成功
            SwiperUtils.setSwiperSuccess();
            Toast.makeText(this, R.string.toast_bindswiper_success, Toast.LENGTH_SHORT).show();
            goToVPos();
            return false;
        } else if (Do_ZztBankList.equals(action)) {
            try {

                BankList bean = (BankList) resp;

                List<Bank> banks = new ArrayList<Bank>();
                if (bean.getList() != null) {
//                    Vector<LuaTable> dataList = LuaTableUtil.getArray(list);
                    // 构造请选择银行
                    // if (Do_GetBanks.equals(action)) {
                    // Bank pleaseSelect = new Bank();
                    // pleaseSelect.setBankId(Bank.INVALID_BANK_ID);
                    // pleaseSelect.setBankName(getString(R.string.please_select_bank));
                    // banks.add(pleaseSelect);
                    // }
                    for (BankList.ListBean bank : bean.getList()) {
                        Bank b = Bank.generateBank(bank);
                        if (null != b) {
                            banks.add(b);
                        }
                    }
                }
                HPLog.d(HPLog.SSX_TAG, banks.toString());
                onBanksLoad(banks, action);
                return false;
            } catch (Exception e) {
                HPLog.e(TAG, "", e);
                return true;
            }
        } else if (Do_ZztBankProvinceList.equals(action)) {

            try {
//                byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
//                LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
//                LuaTable list = (LuaTable) luaTable.rawget("list");
                BankProvinceList bean = (BankProvinceList) resp;


                List<BankProvince> bankProvinces = new ArrayList<BankProvince>();
                if (bean.getList() != null) {
//                    Vector<LuaTable> dataList = LuaTableUtil.getArray(list);
                    for (BankProvinceList.ListBean bankProvince : bean.getList()) {
                        BankProvince province = BankProvince.generateBank(bankProvince);
                        if (null != province) {
                            bankProvinces.add(province);
                        }
                    }
                }
                onBankProvincesLoad(bankProvinces, action);
                return false;
            } catch (Exception e) {
                HPLog.e(TAG, "", e);
                return true;
            }

        } else if (Do_ZztSubBankList.equals(action)) {
//                byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
//                LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
//                LuaTable list = (LuaTable) luaTable.rawget("list");
            List<Bank> banks = new ArrayList<>();
//                if (list != null) {
//                    Vector<LuaTable> dataList = LuaTableUtil.getArray(list);
//                    for (LuaTable table : dataList) {
//                        Bank b = Bank.generateSubBank(table);
//                        if (null != b) {
//                            banks.add(b);
//                        }
//                    }
//                }
            SubBankBean subBankBean = (SubBankBean) resp;
            if (subBankBean.getItems() > 0) {
                for (SubBankBean.ListBean listBean : subBankBean.getList()) {
                    Bank bank = Bank.generateSubBank(listBean);
                    banks.add(bank);
                }
            }
            onBanksLoad(banks, action);
            return false;
        } else if (Do_ZztBankAreaList.equals(action)) {
            BankAreaBean bankAreaBean = (BankAreaBean) resp;
            List<BankArea> bankareas = new ArrayList<>();
            for (BankAreaBean.ListBean listBean : bankAreaBean.getList()) {
                BankArea area = new BankArea();
                area.setBankAreaId(CommonUtils.objectToInt(listBean.getAreaId()));
                area.setBankAreaName(listBean.getAreaName());
                bankareas.add(area);
            }
            HPLog.i("tag-banareas", bankareas.toString());
            onBankAreaLoad(bankareas, action);
            return false;
        }
        return false;
    }

    public boolean dealResponse(String action, Hashtable<String, Object> resp) {
        HPLog.i(TAG, "dealResponse: 1" + action);
        if (action.equals(Do_ZztNewVerifyVersion)) {
            int responseCode = -1;
            try {
                if (resp == null) {
                    return false;
                }
                byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
                LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
                HPLog.i("ZZTongActivity", "luaTable:" + luaTable);
                if (luaTable == null) {
                    return false;
                }

                // 降级交易
                Object dgTrade = luaTable.rawget("dgTrade");
                if (null != dgTrade) {
                    if ("0".equals(dgTrade)) {
                        ZZTConfig.DW_TRADE = false;
                    } else if ("1".equals(dgTrade)) {
                        ZZTConfig.DW_TRADE = true;
                    }
                }

                responseCode = CommonUtils.objectToInt(luaTable.rawget("responseCode"));
                if (responseCode == 0) {
                    ClientEngine.getInstance().saveGlobal(ZZTongActivity.VerifyVersionOK, true);// 只用于登陆时，是否做了版本检测
                    String version = (String) luaTable.rawget("version");
                    String url = (String) luaTable.rawget("url");
                    String description = (String) luaTable.rawget("description");
                    String forcedUpdate = (String) luaTable.rawget("forcedUpdate");
                    // 保存此数据 在HpAboutActivity中用
                    ClientEngine.getInstance().saveGlobal(VERSION, version);
                    ClientEngine.getInstance().saveGlobal(DESCRIPTION, description);
                    ClientEngine.getInstance().saveGlobal(UPDATEURL, url);
                    ClientEngine.getInstance().saveGlobal(FORCEDUPDATE, forcedUpdate);
                    if (TextUtils.isEmpty(url) && TextUtils.isEmpty(description)) {
                        return true;
                    } else {
                        description = description.replace("&", "\n");
                    }
                    String title = getString(R.string.updatetitle, version);
                    String message = description;
                    int result = version.compareTo(ClientEngine.VERSION);
                    if ("0".equals(forcedUpdate) && result > 0) {
                        String mVersion = null;
                        mVersion = sharedPreferences.getString("VERSION", "");
                        HPLog.i("ZZTongActivity", "mVersion:" + mVersion);
                        if (!TextUtils.isEmpty(mVersion) && version.equals(mVersion)) {
                            return true;
                        } else {
                            isforcedCheckVersion(ZZTongActivity.this, title, message, url, version);
                        }
                    } else {
                        checkVersion(this, title, message, url);
                    }
                    return false;
                }
            } catch (Exception e) {
                HPLog.e(TAG, "", e);
                return true;
            }
        } else if (Do_GetSwiperStatus.equals(action)) {
            try {
                byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
                LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
                Object objResponseCode = luaTable.rawget("responseCode");
                Object objErrMsg = luaTable.rawget("errMessage");
                if (null != objResponseCode && null != objErrMsg) {
                    String responseCode = CommonUtils.objectToString(objResponseCode);
                    String errMessage = CommonUtils.objectToString(objErrMsg);
                    showAlertDialog(ZZTongActivity.this, getString(R.string.prompt), errMessage + "[" + responseCode + "]");
                } else {
                    Double status = CommonUtils.objectToDouble(luaTable.rawget("status"));
                    String message = (String) luaTable.rawget("message");

                    SwiperUtils.setSwiperStatus(String.valueOf(status.intValue()), message);
                    // 重新检查刷卡器

                    if (SwiperUtils.isAccountSwiper()) {
                        goToVPos();
                    } else {
                        if (SwiperUtils.canBind()) {
//                            checkVPOS(this, true);
                            goToVPos();
                            return true;
                        } else {
                            showAlertDialog(this, getString(R.string.tip), message, true, new OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    SwiperUtils.cleanSwiperData();
                                    dialog.dismiss();
                                }
                            });
                            return true;
                        }
                    }
                }
            } catch (Exception e) {
                HPLog.e(TAG, "", e);
            }
            // 返回true，避免子类去处理该问题。
            return true;
        } else if (Do_BindSwiper.equals(action)) {
            byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
            LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
            Object objResponseCode = luaTable.rawget("responseCode");
            Object objErrMsg = luaTable.rawget("errMessage");
            if (null != objResponseCode && null != objErrMsg) {
                String responseCode = CommonUtils.objectToString(objResponseCode);
                String errMessage = CommonUtils.objectToString(objErrMsg);
                showAlertDialog(ZZTongActivity.this, getString(R.string.prompt), errMessage);
                return false;
            } else {
                // 绑定刷卡器成功
                SwiperUtils.setSwiperSuccess();
                Toast.makeText(this, R.string.toast_bindswiper_success, Toast.LENGTH_SHORT).show();
                // 改变连接的状态2.1版本 WatingForBindDevice
            /*
             * if (this instanceof WatingForBindDevice) { HPLog.i(TAG,
			 * "Do_BindSwiper WatingForBindDevice doVPOS");
			 * ApiSwiperFactory.getInstance().doVPOS(); goBack(); }
			 */
                goToVPos();
                // 返回true，避免子类去处理该问题。
                return true;
            }
        } else if (Do_SendPhoneCode.equals(action)) {
            byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
            LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
            Object objResponseCode = luaTable.rawget("responseCode");
            Object objErrMsg = luaTable.rawget("errMessage");
            if (null != objResponseCode && null != objErrMsg) {
                String responseCode = CommonUtils.objectToString(objResponseCode);
                String errMessage = CommonUtils.objectToString(objErrMsg);
                showAlertDialog(ZZTongActivity.this, getString(R.string.prompt), errMessage + "[" + responseCode + "]");
                return false;
            } else {
                Toast.makeText(ZZTongActivity.this, "发送验证码成功！", Toast.LENGTH_SHORT).show();
                return true;
            }
        } else if (Do_ZztBankList.equals(action)) {
            try {
                byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
                LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
                LuaTable list = (LuaTable) luaTable.rawget("list");
                List<Bank> banks = new ArrayList<Bank>();
                if (list != null) {
                    Vector<LuaTable> dataList = LuaTableUtil.getArray(list);
                    // 构造请选择银行
                    // if (Do_GetBanks.equals(action)) {
                    // Bank pleaseSelect = new Bank();
                    // pleaseSelect.setBankId(Bank.INVALID_BANK_ID);
                    // pleaseSelect.setBankName(getString(R.string.please_select_bank));
                    // banks.add(pleaseSelect);
                    // }
                    for (LuaTable table : dataList) {
//                        Bank b = Bank.generateBank(table);
//                        if (null != b) {
//                            banks.add(b);
//                        }
                    }
                }
                onBanksLoad(banks, action);
                return false;
            } catch (Exception e) {
                HPLog.e(TAG, "", e);
                return true;
            }
        } else if (Do_ZztBankProvinceList.equals(action)) {

            try {
                byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
                LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
                LuaTable list = (LuaTable) luaTable.rawget("list");
                List<BankProvince> bankProvinces = new ArrayList<BankProvince>();
                if (list != null) {
                    Vector<LuaTable> dataList = LuaTableUtil.getArray(list);
                    for (LuaTable table : dataList) {
//                        BankProvince province = BankProvince.generateBank(table);
//                        if (null != province) {
//                            bankProvinces.add(province);
//                        }
                    }
                }
                onBankProvincesLoad(bankProvinces, action);
                return false;
            } catch (Exception e) {
                HPLog.e(TAG, "", e);
                return true;
            }

        } else if (Do_ZztBankAreaList.equals(action)) {
            try {
                byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
                if (ZZTConfig.testData) {
                    String mockdata = "data={items=\"4\",list={{areaId=\"11\",areaName=\"天津\"},{areaId=\"12\",areaName=\"北京\"},{areaId=\"13\",areaName=\"上海\"},{areaId=\"14\",areaName=\"山东\"}}}";
                    data = mockdata.getBytes("UTF-8");
                    isDataCompile = false;
                }
                LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
                LuaTable list = (LuaTable) luaTable.rawget("list");
                List<BankArea> bankareas = new ArrayList<BankArea>();
                if (list != null) {
                    Vector<LuaTable> dataList = LuaTableUtil.getArray(list);
                    for (LuaTable table : dataList) {
                        BankArea area = BankArea.generateBank(table);
                        if (null != area) {
                            bankareas.add(area);
                        }
                    }
                }
                HPLog.i("tag-banareas", bankareas.toString());
                onBankAreaLoad(bankareas, action);
                return false;
            } catch (Exception e) {
                HPLog.e(TAG, "", e);
                return true;
            }
        } else if (Do_ZztSubBankList.equals(action)) {
            try {
                byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
                LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
                LuaTable list = (LuaTable) luaTable.rawget("list");
                List<Bank> banks = new ArrayList<Bank>();
                if (list != null) {
                    Vector<LuaTable> dataList = LuaTableUtil.getArray(list);
//                    for (LuaTable table : dataList) {
//                        Bank b = Bank.generateSubBank(table);
//                        if (null != b) {
//                            banks.add(b);
//                        }
//                    }
                }
                onBanksLoad(banks, action);
                return false;
            } catch (Exception e) {
                HPLog.e(TAG, "", e);
                return true;
            }

        }
        return false;
    }

    /**
     * 获取到主banks后的回调
     *
     * @param banks
     */
    public void onBanksLoad(List<Bank> banks, String action) {

    }

    /**
     * 获取到省份BankProvinces后的回调
     *
     * @param province
     * @param action
     */
    public void onBankProvincesLoad(List<BankProvince> province, String action) {

    }

    /**
     * 获取到省份BankArea后的回调
     *
     * @param area
     * @param action
     */
    public void onBankAreaLoad(List<BankArea> area, String action) {

    }

    /**
     * 版本检测处理流程
     */
    public void checkVersion(final ZZTongActivity activity, String title, String message, final String url) {
        showAlertDialog(activity, title, message, false, getResources().getString(R.string.immediately_update), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    goToDownloadActivity(activity, url);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }, null, null, null, null);
    }

    protected void goToDownloadActivity(Activity activity, String url) {

        Intent intent = new Intent(activity, DownloadApkActivity.class);
        intent.putExtra(UPDATEURL, url);
        activity.startActivity(intent);
    }

    /**
     * 版本检测处理流程
     *
     * @param activity
     * @param title
     * @param message
     * @param url
     * @param version
     */
    public void isforcedCheckVersion(final ZZTongActivity activity, String title, String message, final String url, final String version) {
        showAlertDialog(activity, title, message, false, getResources().getString(R.string.immediately_update), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {

                    // ClientEngine.getInstance().browse(activity, url, false);
                    goToDownloadActivity(activity, url);

                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }, getResources().getString(R.string.not_update), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 暂时不更新，但用户可以进入应用，并使用功能

                dialog.dismiss();

                long currentTimeMillis = System.currentTimeMillis();
                AipSharedPreferences.getInstance(ZZTongActivity.this).setVerifyLastTime(currentTimeMillis);
                if (ZZTongActivity.this instanceof WelcomeActivity) {
                    startActivity(new Intent(ZZTongActivity.this, LoginActivity.class));
                }
            }
        }, getResources().getString(R.string.no_longer_remind), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int arg1) {
                // 用户同样可以进入应用，但是，下次检测版本的时候，如果是同一版本，不再提示，如果有更高版本，会再提示。
                Editor editor = sharedPreferences.edit();// 获取编辑器
                editor.putString("VERSION", version);
                editor.commit();
                HPLog.i("mVersion", version);
                dialog.dismiss();
                if (ZZTongActivity.this instanceof WelcomeActivity) {
                    startActivity(new Intent(ZZTongActivity.this, LoginActivity.class));
                }
            }
        });
    }

    /**
     * 默认做网络检查，并且显示加载中的对话框
     *
     * @param activity 接受回调的Activity
     * @param action   标示哪个服务
     * @param params   该服务的参数
     * @return 返回为true, 表示发出网络请求
     */
    public boolean doPost(final BaseActivity activity, final String action, final Hashtable<String, String> params) {
        return doPost(activity, action, params, true);
    }

    /**
     * 默认做网络是否打开的检查
     *
     * @param activity    接受回调的Activity
     * @param action      标示哪个服务
     * @param params      该服务的参数
     * @param showLoading 请求该访问的时候，是否显示对话框
     * @return 返回为true, 表示发出网络请求
     */
    public boolean doPost(final BaseActivity activity, final String action, final Hashtable<String, String> params, boolean showLoading) {
        return doPost(true, activity, action, params, showLoading);
    }

    /**
     * 请求网络访问
     *
     * @param checkNet    做网络请求之前是否，检查网络
     * @param activity    接受回调的Activity
     * @param action      标示哪个服务
     * @param params      该服务的参数
     * @param showLoading 请求该访问的时候，是否显示对话框
     * @return 返回为true, 表示发出网络请求
     */
    protected boolean doPost(boolean checkNet, final BaseActivity activity, final String action, final Hashtable<String, String> params, boolean showLoading) {
        if (checkNet && checkNetAndAlert(activity)) {
            return false;
        }
        if (showLoading) {
            this.showProgressDialog(this, getString(R.string.pleasewait));
        } else {
            HPLog.i(TAG, "Action:" + action + "showLoading:" + showLoading);
        }
        HttpSFTConnector.doVolleyPost(activity, action, params, checkNet, -1);
        return true;
    }

    public boolean doJsonPost(final BaseActivity activity, final String action, final Class<? extends ResponseBean> cls, final Hashtable<String, String> params) {
        return doJsonPost(true, activity, action, cls, params, true);
    }


    public boolean doJsonPost(boolean checkNet, final BaseActivity activity, final String action, final Class<? extends ResponseBean> cls, final Hashtable<String, String> params, boolean showLoading) {
        if (checkNet && checkNetAndAlert(activity)) {
            return false;
        }
        HPLog.i(TAG, "doJsonPost Action:" + action + " showLoading:" + showLoading);
        if (showLoading) {
            this.showProgressDialog(this, getString(R.string.pleasewait));
        }
        HttpSFTConnector.doVolleyJsonPost(activity, action, cls, params, checkNet, -1);
        return true;
    }

    public boolean doJsonPost(boolean checkNet, final BaseActivity activity, final String action, final Class<? extends ResponseBean> cls, final Hashtable<String, String> params, boolean showLoading, boolean isInVisible) {
        if (checkNet && checkNetAndAlert(activity)) {
            return false;
        }
        HPLog.i(TAG, "doJsonPost Action:" + action + " showLoading:" + showLoading);
        if (showLoading) {
            if (isInVisible) {
                this.showInsvisableProgressDialog(this, getString(R.string.pleasewait));

            } else {
                this.showProgressDialog(this, getString(R.string.pleasewait));
            }
        }
        HttpSFTConnector.doVolleyJsonPost(activity, action, cls, params, checkNet, -1);
        return true;
    }


    /***
     * asynctask httpUrlconnection request
     * @param activity activity
     * @param action 请求action
     * @param cls 需要解析的Bean
     * @param params 请求参数
     * @param showLoading 是否显示Loading
     */
    public void asyncHttpPost(final BaseActivity activity, final String action, final Class<? extends ResponseBean> cls, final Hashtable<String, String> params, boolean showLoading) {
        if (!checkNetAndAlert(activity)) {
            if (showLoading) {
                this.showProgressDialog(this, getString(R.string.pleasewait));
            }
            HttpSFTConnector.asyncPostWithHttpUrlConnection(activity.getApplicationContext(), action, params, cls, activity, true);
        }
    }

    /***
     * 根据TAG取消对应的请求
     *
     * @param tag
     */

    public void cancelVolleyRequest(String tag) {
        HPLog.i(TAG, "cancel request→" + tag);
        if (requestQueue != null) requestQueue.cancelAll(tag);
    }

    /***
     * @param checkNet
     * @param activity
     * @param action
     * @param params
     * @param showLoading
     * @param loadingStr
     * @param timeout
     * @return
     */
    public boolean doPost(boolean checkNet, final BaseActivity activity, final String action, final Hashtable<String, String> params, boolean showLoading, String loadingStr, int timeout) {
        if (checkNet && checkNetAndAlert(activity)) {
            return false;
        }
        if (showLoading) {
            if (TextUtils.isEmpty(loadingStr))
                this.showProgressDialog(this, getString(R.string.pleasewait));
            else this.showProgressDialog(this, loadingStr);
        }
        HttpSFTConnector.doVolleyPost(activity, action, params, checkNet, timeout);
        return true;
    }

    /**
     * 检测网络，如果网络不可用，弹出提示，并返回为true;否则返回为false
     *
     * @return
     */
    public boolean checkNetAndAlert(final BaseActivity activity) {
        if (!checkNetworkInfo()) {
            // 网络未打开
            this.showAlertDialog(this, getString(R.string.tip), getString(R.string.no_web), false, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    // 如果3G网络和wifi网络都未连接，且不是处于正在连接状态 则进入Network
                    // Setting界面 由用户配置网络连接
                    dialog.dismiss();
//                    activity.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));// 进入无线网络配置界面
                    exitapp();//新版本需求，客户端检测没有网络直接退出APP 2017.3.16
                }
            });
            return true;
        }
        return false;
    }

    String mscn;

    @Override
    public void onBatteryLow() {
        this.showAlertDialog(this, getString(R.string.tip), getString(R.string.battery_low_tips), true, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 刷卡界面必须重写这个函数
     */
    @Override
    public void onShownPwd() {

    }

    private ProgressDialog mPd = null;

    private void closeSwiperWaitingDialog() {
        try {
            if (null != mPd) {
                mPd.dismiss();
                mPd = null;
            }
        } catch (Exception e) {
            HPLog.i(TAG, "", e);
        }
    }

    @Override
    public void onSwiperStatus(int status, int result, String pan, boolean isDownlTrd) {
        HPLog.e("onSwiperStatus", "onSwiperStatus " + result);
        this.closeProgressDialog();
        switch (result) {
            case ISwiperListener.Swiper_Plug_In:
                HPLog.e("ZZtong", " 音频口已链接-------------");
                // 音频口已连接
                SwiperUtils.setSwiperStatus(true);
                String csn = getCSN();
                mscn = csn;
                if (TextUtils.isEmpty(csn)) {
                    closeSwiperWaitingDialog();
                    // mPd = DialogFactory.showProgressDialog(this,
                    // getString(R.string.devauthenticating));
                    Toast.makeText(this, R.string.devauthenticating, Toast.LENGTH_SHORT).show();
                    doDeviceConnect();//连接设备
                } else {
                    SwiperUtils.saveCsn(csn);
                }
                break;
            case ISwiperListener.Swiper_Plug_Off:
                HPLog.e("ZZtong", " 音频口未链接-------------");
                // 音频口未连接
                SwiperUtils.cleanSwiperData();
                closeSwiperWaitingDialog();
                // SwiperUtils.setSwiperStatus(false);
                onSwiperPlugOff();
                // SwiperUtils.saveCsn(null);
                if (this instanceof ConnectSwiperActivity) {
                    goBack();
                }
                break;
            case ISwiperListener.Swiper_OK:
                HPLog.e("ZZtong", " 检查是否合法csn");
                HPLog.e("ZZtong", "ZZTONG_---->ISwiperListener.Swiper_OK-->status=" + status);
                if (status == ISwiperListener.Status_Connect) {
                    csn = getCSN();
                    closeSwiperWaitingDialog();
                    if (!ZZTConfig.ENV.SWIPERCSN) {
                        csn = ZZTConfig.testerCsn;
                    }
                    HPLog.e("ZZTongActivity", "use csn:" + csn);
                    // 老刷卡器，不支持
                    if (!CommonUtils.isNewSwiper(csn)) {
                        csnWarning(getString(R.string.device_with_incompatible));
                    } else {
                        SwiperUtils.saveCsn(csn);
                        // checkCsn();
                        onConnectSuccess();
                        // csnWarning(getString(R.string.device_succesed));
                    }
                }
                break;
            case ISwiperListener.Swiper_Timeout:
                HPLog.e("ZZTongActivity", " 刷卡超时-------------");
                break;
            case ISwiperListener.Swiper_Error:
                if (status == ISwiperListener.Status_Connect) {
                    closeSwiperWaitingDialog();
                    HPLog.e("ZZTongActivity", " 刷卡错误-------------");
                    SwiperUtils.saveCsn(null);
                    AipSharedPreferences.getInstance(this).setLastSelectDevice(null);
                    csnWarning(getString(R.string.no_device));
                }
                break;
            case ISwiperListener.Swiper_Cancel:
                HPLog.e("ZZTongActivity", "  取消刷卡-------------");
                goBack();
                break;
        }
    }

    /**
     * 重写该函数，请注意在最后调用父类来处理，加密失败后重试等相关问题。
     */
    @Override
    public void onSwiperStatus(int status, int result, String keyIndex, String encData, String plainData) {
        if (ISwiperListener.Status_EncyptData == status) {
            if (ISwiperListener.Swiper_OK == result && !TextUtils.isEmpty(encData)) {
                this.mEncRetryCount = 0;
            } else {
                this.mEncRetryCount++;
                if (this.mEncRetryCount >= MAXRETRIES) {
                    HPLog.e("onSwiperStatus", "keyIndex:" + keyIndex + ",encData:" + encData + ",plainData:" + plainData);
                    swiperWarning(getResources().getString(R.string.warning_ency_failed));
                } else {
                    if (ISwiperListener.KeyDataIndex.equals(keyIndex)) {
                        doEncryData(plainData);
                    } else if (ISwiperListener.MacDataIndex.equals(keyIndex)) {
                        doMac(plainData);
                    }
                }
            }
        }
        HPLog.e("onSwiperStatus", "status:" + status);
    }

    @Override
    public void onSwiperStatus(int status, int result, HashMap<String, String> hmData) {
        HPLog.e("onSwiperStatus", "HashMap");
    }

    @Override
    public void onSwiperStatus(int status, int result, String encPwd) {
        HPLog.e("onSwiperStatus", "encPwd");
    }

    @Override
    public long getId() {
        return CREATE_TIME;
    }

    // -------------------封装刷卡器的方法BEGIN---------------
    /**
     * 请在开始具体业务的时候，务必设置刷卡器的模式
     *
     * @param m
     */
    private long mLastClickTime = 0;

    private void setMode(final SwiperMode m, final Runnable successTask) {
        if (AccountUtils.getAccountStatus(this) == AccountUtils.AccountStatus.NOUPLOAD) {
            if (checkVPOS(this, true)) {
                // 没有上传资质审核信息，提醒用户提交资质审核
                showAlertDialog(this, getString(R.string.tip), getString(R.string.QualificationsPromptVOP_2), true, new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (checkSwiperOk(ZZTongActivity.this, true)) {
                            // GOTO 提交资质审核界面
                            startActivity(getComposeIntent());
                        }
                        dialog.dismiss();
                    }
                }, null);
            }
            return;
        }
//        HPLog.i(HPLog.YL_TAG, "setMode:3");

        mLastClickTime = SystemClock.elapsedRealtime();
        // 先检测刷卡器的状态。
        if (!checkCsn()) {
            return;
        }


        new MyAsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                HPLog.i(TAG, "ApiSwiperFactory.getInstance().setMode(m):" + m);
                return ApiSwiperFactory.getInstance().setMode(m);
            }

            @Override
            protected void onPostExecute(Boolean result) {
                ZZTongActivity.this.closeProgressDialog();
                if (result.booleanValue() == true) {
                    ZZTongActivity.this.runOnUiThread(successTask);
                } else {
                    ZZTongActivity.this.showAlertDialog(ZZTongActivity.this, R.string.tip, R.string.warning_ency_failed);
                }
            }

            @Override
            protected void onPreExecute() {
                ZZTongActivity.this.showProgressDialog(ZZTongActivity.this, ZZTongActivity.this.getString(R.string.loading));
            }
        }.execute();
    }

    public void setMode(final SwiperMode m, boolean isCheckBandSwiper, final Runnable successTask) {
        SwiperUtils.setBandSwiperStatus(isCheckBandSwiper);
        setMode(m, successTask);
    }

    public Intent getComposeIntent() {
        Intent i = new Intent(ZZTConstant.COMPOSE_ACTION);
        // 确保在应用内跳转
        i.setPackage(getPackageName());
        return i;
    }

    public String getCSN() {

        return ApiSwiperFactory.getInstance().getCSN();
    }

    public String getFactor() {
        String factor = null;
        factor = ApiSwiperFactory.getInstance().getFactor();
        return factor;
    }

    public void clearFactor() {
        ApiSwiperFactory.getInstance().clearFactor();
    }

    public String getFactorTime() {
        String factor = getFactor();
        if (null != factor) {
            return factor.substring(0, 14);
        }
        return null;
    }

    /**
     * 连接设备
     */
    public void doDeviceConnect() {
        ApiSwiperFactory.getInstance().doDeviceConnect(getId());
    }

    public void doRegisterPwd(String cardNo) {
        ApiSwiperFactory.getInstance().doRegisterPwd(cardNo, getId());
    }

    public void doSwipe() {
        ApiSwiperFactory.getInstance().doSwipe(getId());
    }

    public void doInputPwd() {
        ApiSwiperFactory.getInstance().doInputPwd(getId());
    }

    /**
     * 确认金额-刷卡-输密码
     *
     * @param amount
     */
    public void doAffirmAmount(String amount) {
        ApiSwiperFactory.getInstance().doAffirmAmount(amount, getId());
    }

    public void doMac(String data) {
        ApiSwiperFactory.getInstance().doMac(data, getId());
    }

    public void doBankListMac() {
        ApiSwiperFactory.getInstance().doBankListMac(getId());
    }

    /**
     * MAC计算
     *
     * @param data
     */
    public void doEncryData(String data) {
        ApiSwiperFactory.getInstance().doEncryData(data, getId());
    }

    public void registerListener(ISwiperListener is) {
        ApiSwiperFactory.getInstance().registerListener(is);
    }

    public void unRegisterListener(ISwiperListener is) {
        ApiSwiperFactory.getInstance().unRegisterListener(is);
    }

    public void onSwiperPlugOff() {
        HPLog.i("ZZTongActivity", "You should override onSwiperPlugOff method to do your own work!");
        if (!TextUtils.isEmpty(SwiperUtils.getCsn())) {
            Toast.makeText(this, R.string.device_failed, Toast.LENGTH_LONG).show();
        } else {
            ApiSwiperFactory.getInstance().clearSwiper(null);
            Toast.makeText(this, R.string.no_device, Toast.LENGTH_LONG).show();
        }
    }

    // -------------------封装刷卡器的方法END---------------
    // actionbar and tab
    @Override
    public void onClick(View v) {
        if (null == v) {
            goBack();
            return;
        }
        int i = v.getId();
        /*
         * if (i == R.id.tab_account) { onAccountTab(v); } else if (i ==
		 * R.id.tab_function) { onFunctionTab(v); } else if (i ==
		 * R.id.tab_transfer) { onTransferTab(v); }
		 */
    }

    public void onAccountTab(View v) {
        if (this instanceof MainActivity) return;
        Intent t = new Intent(this, MainActivity.class);
        t.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        t.putExtra(FRAGMENTFLAG, ZZTConstant.FRAGMENT_FLAG_MY);
        this.startActivity(t);
    }

    public void goToMainActivity(String tag) {
        Intent t = new Intent(this, MainActivity.class);
        t.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        t.putExtra(FRAGMENTFLAG, tag);
        this.startActivity(t);
    }

    public void onTransferTab(View v) {
        if (this instanceof MainActivity) return;
        Intent t = new Intent(this, MainActivity.class);
        t.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        t.putExtra(FRAGMENTFLAG, ZZTConstant.FRAGMENT_FLAG_RECEIVABLES);
        HPLog.e("FDL", "------onTransferTab-----startActivity---");
        this.startActivity(t);
    }

    public void onFunctionTab(View v) {
        if (this instanceof MainActivity) return;
        Intent t = new Intent(this, MainActivity.class);
        t.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        t.putExtra(FRAGMENTFLAG, ZZTConstant.FRAGMENT_FLAG_HOME);
        this.startActivity(t);
    }

    /**
     * 获取用户地理位置，并保存起来。 没有打开GPS，提醒用户去设置界面打开。
     *
     * @param force true,强制用户去那个界面打开;false,用户可以取消
     *              获取到的地理位置内容，最后会存在clientEngine里面。这个方法，仅仅是请求地理位置，用在需要地理位置之前。
     *              如果在使用的时候，发现没有地理位置，不要影响程序的运行。
     */
    public boolean requestCurrentLocation(boolean force) {
        if (!CommonUtils.isLocationServiceOpen(this)) {
            // showDialog
            String message = this.getString(R.string.message_alert_gps);
            String title = this.getString(R.string.tip);
            DialogInterface.OnClickListener okDI = new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    try {
                        Intent gotoGPS = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        ZZTongActivity.this.startActivity(gotoGPS);
                    } catch (ActivityNotFoundException anfe) {
                        anfe.printStackTrace();
                    }
                    dialog.dismiss();
                }
            };
            if (true != force) {
                DialogInterface.OnClickListener cancelDI = new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                };
                showAlertDialog(this, title, message, true, okDI, cancelDI);
            } else {
                // showAlertDialog(this, title, okDI);
                showAlertDialog(this, title, message, false, okDI);
            }
            return false;
        } else {
            if (AndPermission.hasPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
                ZZTApplication application = (ZZTApplication) ZZTongActivity.this.getApplication();
                application.requestLocation();
                return true;
            } else {
                AndPermission.with(this).requestCode(PermissionRequestCode.REQUEST_CODE_PERMISSION_LOCATION).
                        permission(Manifest.permission.ACCESS_FINE_LOCATION).
                        rationale(new RationaleListener() {
                            @Override
                            public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                                AndPermission.rationaleDialog(ZZTongActivity.this, rationale).show();
                            }
                        }).send();
                return false;
            }
        }
    }

    /**
     * 获取用户地理位置， 没有打开GPS，提醒用户去设置界面打开。
     *
     * @return
     */
    public void getCurrentLocation() {
        // 如果没有打开地理位置，提醒，并返回。
        if (!requestCurrentLocation(true)) {
            return;
        }
        showAlertDialog(this, getString(R.string.tip), getString(R.string.Gets_address), true, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    Intent gotoGPS = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    ZZTongActivity.this.startActivity(gotoGPS);
                } catch (ActivityNotFoundException anfe) {
                    anfe.printStackTrace();
                }
                dialog.dismiss();
            }
        }, new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AndPermission.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 动态权限获取成功后的回调，如子类动态权限获取成功后需要处理不同的逻辑，必须重写此方法
     *
     * @param requestCode      权限code
     * @param grantPermissions 权限列表
     */
    @Override
    public void onSucceed(int requestCode, List<String> grantPermissions) {
        if (requestCode == PermissionRequestCode.REQUEST_CODE_PERMISSION_LOCATION) {
            Toast.makeText(ZZTongActivity.this, R.string.message_location_succeed, Toast.LENGTH_SHORT).show();
            ZZTApplication application = (ZZTApplication) ZZTongActivity.this.getApplication();
            application.requestLocation();
        } else if (requestCode == PermissionRequestCode.REQUEST_CODE_PERMISSION_CAMERA) {
            openCustomCameraActivity();
        }
    }

    @Override
    public void onFailed(int requestCode, List<String> deniedPermissions) {
        if (requestCode == PermissionRequestCode.REQUEST_CODE_PERMISSION_LOCATION) {
            Toast.makeText(ZZTongActivity.this, R.string.message_location_failed, Toast.LENGTH_SHORT).show();
        } else if (requestCode == PermissionRequestCode.REQUEST_CODE_PERMISSION_CAMERA) {
            Toast.makeText(ZZTongActivity.this, R.string.message_camera_failed, Toast.LENGTH_SHORT).show();
        } else if (requestCode == PermissionRequestCode.REQUEST_CODE_PERMISSION_AUDIO) {
            Toast.makeText(ZZTongActivity.this, R.string.message_audio_failed, Toast.LENGTH_SHORT).show();
        } else if (requestCode == PermissionRequestCode.REQUEST_CODE_PERMISSION_CALL_PHONE) {
            Toast.makeText(this, R.string.message_phone_failed, Toast.LENGTH_SHORT).show();
        } else if (requestCode == PermissionRequestCode.REQUEST_CODE_PERMISSION_STORAGE) {
            Toast.makeText(this, R.string.message_storage_failed, Toast.LENGTH_SHORT).show();
        } else if (requestCode == PermissionRequestCode.REQUEST_CODE_PERMISSION_READ_PHONE_STATE_AND_STORAGE) {
            Toast.makeText(this, R.string.message_storage_and_phonestate_failed, Toast.LENGTH_SHORT).show();
        } else if (requestCode == PermissionRequestCode.REQUEST_CODE_CAMERA_GETCARDNO) {
            Toast.makeText(this, R.string.message_camera_failed, Toast.LENGTH_SHORT).show();
        } else if (requestCode == REQUEST_CODE_FINDLOCATION) {
            Toast.makeText(this, R.string.message_location_failed, Toast.LENGTH_SHORT).show();
        }
        if (AndPermission.hasAlwaysDeniedPermission(ZZTongActivity.this, deniedPermissions)) {
            // 第一种：用默认的提示语。
//            AndPermission.defaultSettingDialog(ZZTongActivity.this, PermissionRequestCode.REQUEST_CODE_SETTING).show();

            // 第二种：用自定义的提示语。
            AndPermission.defaultSettingDialog(this, requestCode).setTitle("权限申请失败").setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败，请您到设置页面手动授权，否则功能无法正常使用！").setPositiveButton("好，去设置").show();

//            第三种：自定义dialog样式。
//            SettingService settingHandle = AndPermission.defineSettingDialog(this, REQUEST_CODE_SETTING);
//            你的dialog点击了确定调用：
//            settingHandle.execute();
//            你的dialog点击了取消调用：
//            settingHandle.cancel();
        }
    }

    /**
     * 检测刷卡器的状态，如果刷卡器插入了。 主要用于，登录后，或注册成功后调用。如果在用户还没有登录或者还没有注册的时候，已经插入刷卡器，那用户登录后
     * 就应该检测该刷卡器状态。
     */
    public void getCsnStatusIfReady() {
        if (AccountUtils.getAccountStatus(this) != AccountUtils.AccountStatus.NOUPLOAD) {
            mAlertBindSwiper = true;
            checkVPOS(this, false);
        }
    }

    /**
     * 主要用户提交资质材料前，调用检测刷卡器的状态；其他情况，请不要使用
     *
     * @param activity
     * @param alertIfNotReady
     * @return
     */
    public boolean checkSwiperOk(final ZZTongActivity activity, boolean alertIfNotReady) {
        mAlertBindSwiper = false;
        return checkVPOS(activity, alertIfNotReady);
    }

    /**
     * 用于检测刷卡器的状态。 先检测版本，然后检测刷卡器。
     *
     * @param activity
     * @param alertIfNotReady
     * true表示，检测前期的工作的时候，提示用户（例如请插入刷卡器、不兼容该刷卡器等）。 false表示，不提示用户
     * @return
     */
    private volatile boolean mAlertBindSwiper = true;

    public boolean checkVPOS(final ZZTongActivity activity, boolean alertIfNotReady) {
        if (!SwiperUtils.isSwiperConnected() || !SwiperUtils.isSwiperOK()) {
            // 请插入刷卡器
            SwiperDeviceSelectInfo swiperDeviceSelectInfo = AipSharedPreferences.getInstance(this).getLastSelectDevice();
            if (swiperDeviceSelectInfo != null && swiperDeviceSelectInfo.selectType != -1) {

                if (swiperDeviceSelectInfo.selectType == SwiperDeviceSelectInfo.DEVICE_TYPE_BLUETOOTH) {
                    SwiperBluetoothDeviceSelectInfo swiperBluetoothDeviceSelectInfo = AipSharedPreferences.getInstance(this).getSwiperBluetoothDeviceInfo();
                    if (swiperBluetoothDeviceSelectInfo == null || TextUtils.isEmpty(swiperBluetoothDeviceSelectInfo.getIdentifier())) {
                        if (alertIfNotReady) {
                            showAlertDialog(activity, getString(R.string.tip), getString(R.string.inputswiper), true, new OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent swiperIntent = new Intent(ZZTongActivity.this, ConnectSwiperActivity.class);
                                    startActivityForResult(swiperIntent, ZZTConstant.CONNECT_SWIPER_CODE);
                                    dialog.dismiss();
                                }
                            }, null);
                        }
                        return false;
                    }
                }
                Intent swiperIntent = new Intent(ZZTongActivity.this, ConnectSwiperActivity.class);
                swiperIntent.putExtra("SWIPER_STATE", ConnectSwiperActivity.SWIPER_SELECT_AUTO_CONNECT);
                startActivityForResult(swiperIntent, ZZTConstant.CONNECT_SWIPER_CODE);
                return false;
            } else {
                if (alertIfNotReady) {
                    showAlertDialog(activity, getString(R.string.tip), getString(R.string.inputswiper), true, new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent swiperIntent = new Intent(ZZTongActivity.this, ConnectSwiperActivity.class);
                            startActivityForResult(swiperIntent, ZZTConstant.CONNECT_SWIPER_CODE);
                            dialog.dismiss();
                        }
                    }, null);
                }
                return false;
            }
        }
        // 强制要求打开gps，即使有可能address已经拿到了。
        if (!requestCurrentLocation(true)) {
            return false;
        }
        HPLog.i(HPLog.YL_TAG, "checkVPOS Do_GetwiperStatus-------isNeedGetSwiperStatus:" + SwiperUtils.isNeedGetSwiperStatus());

//        if (SwiperUtils.isNeedGetSwiperStatus() || !SwiperUtils.isAccountSwiper()) {
        if (SwiperUtils.isNeedGetSwiperStatus()) {

            String address = (String) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_ADDRESS);
            if (!TextUtils.isEmpty(address)) {
                HPLog.i(HPLog.YL_TAG, "checkVPOS Do_GetSwiperStatus-------post");
                commonRequest(Do_GetSwiperStatus);
            } else {
                getCurrentLocation();
            }
            return false;
        }

        if (AccountUtils.AccountStatus.NOUPLOAD == AccountUtils.getAccountStatus(this)) {
            // 没有上传资质材料的时候。只有当该刷卡器，不是当前账户的，且处于可以绑定的状态下，才通过检测。

            if (!SwiperUtils.isAccountSwiper() && SwiperUtils.canBind()) {
//                 csnSuccessCallback();
                return true;
            } else {

                String message = SwiperUtils.getSwiperDes();
                showAlertDialog(activity, activity.getString(R.string.tip), message, true, new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        SwiperUtils.cleanSwiperData();
                        if (ZZTongActivity.this instanceof ConnectSwiperActivity) {
                            goBack();
                        }
                        dialog.dismiss();
                    }
                });
                return false;
            }
        } else {

            if (!SwiperUtils.isAccountSwiper()) {

                if (SwiperUtils.canBind()) {

                    // 提示绑定流程
                    if (mAlertBindSwiper) {
                        showBindSwiperDialog(activity);
                    } else {
                        // csnSuccessCallback();
                        return true;
                    }
                } else {
                    if (SwiperUtils.gettBandSwiperStatus()) {

                        return true;
                    } else {
                        // 显示各种其他状态的提示信息。
                        String message = SwiperUtils.getSwiperDes();
                        showAlertDialog(activity, activity.getString(R.string.tip), message, true, new OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                SwiperUtils.cleanSwiperData();
                                if (ZZTongActivity.this instanceof ConnectSwiperActivity) {
                                    goBack();
                                }
                                dialog.dismiss();
                            }
                        });
                    }
                }
                return false;
            }
            // csnSuccessCallback();
            return true;
        }
        // 检查超级转账和新刷卡器的问题，放在登录之后
        // if (ZZTongActivity.Action_SuperTransfer == mAction
        // && !CommonUtils.isNewSwiper(SwiperUtils.getCsn())) {
        // showAlertDialog(this, null,
        // getResources().getString(R.string.warning_new_swiper_only));
        // return false;
        // }

        // csnSuccessCallback();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ZZTConstant.CONNECT_SWIPER_CODE) {
            if (resultCode == Activity.RESULT_OK) {
//                String csn = ApiSwiperFactory.getInstance().getCSN();
//                HPLog.i(HPLog.YL_TAG, "CONNECT_SWIPER_SUCCESS CSN:"+csn);
//                SwiperUtils.saveCsn(csn);
                goToVPos();
            }
        }
    }

    /**
     * 检查csn的状态
     *
     * @return true 表示用户可以使用。否则该刷卡器不可以使用
     */
    private boolean checkCsn() {
        if (!TextUtils.isEmpty(AccountUtils.getAccountName(this))) {
            // 没有上传资质，我们还是会去获取csn的使用情况；如果上传了，我们就要提醒用户去绑定
            mAlertBindSwiper = AccountUtils.AccountStatus.NOUPLOAD != AccountUtils.getAccountStatus(this);
            return checkVPOS(this, true);
        }
        return false;
    }

    private void showBindSwiperDialog(final ZZTongActivity activity) {
        showAlertDialog(activity, getString(R.string.tip), getString(R.string.message_alert_bindswiper), true, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                String csn = SwiperUtils.getCsn();
                if (TextUtils.isEmpty(csn)) {
                    HPLog.e("ZZTongActivity", "checkVpos  showBindSwiperDialog:csn  is null");
                    Toast.makeText(activity, getString(R.string.no_device), Toast.LENGTH_LONG).show();
                    SwiperUtils.cleanSwiperData();
                    return;
                }
                requestBindSwiper(csn);
                dialog.dismiss();
            }
        });
    }

    /**
     * 绑定该csn到当前账户。发送请求到后台
     *
     * @param csn 明文
     */
    public void requestBindSwiper(String csn) {
        Hashtable<String, String> p = new Hashtable<String, String>();
        String phone = AccountUtils.getAccountPhone(this);
        if (!TextUtils.isEmpty(phone)) {
            p.put(BaseProtocolKey.PHONE, SecureManager.getInstance().des(phone, 1, null));
            p.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(AccountUtils.getAccountName(this), 1, null));
            p.put(CardProtocolKey.CSN_KEY, SecureManager.getInstance().des(csn, 1, null));
            p.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
            doJsonPost(ZZTongActivity.this, Do_BindSwiper, ResponseBean.class, p);
        }
    }

    private void commonRequest(String action) {
        String csn = SwiperUtils.getCsn();
        HPLog.i("ZZTongActivity", "checkVpos  commonRequest:csn" + csn);
        if (TextUtils.isEmpty(csn)) {
            HPLog.e("ZZTongActivity", "checkVpos  commonRequest:csn  is  111111111111111");
            showAlertDialog(this, getString(R.string.tip), getString(R.string.no_device));
            SwiperUtils.cleanSwiperData();
            return;
        }
        Hashtable<String, String> paramers = new Hashtable<String, String>();
        String accountName = AccountUtils.getAccountName(this);
        appendAddresses(paramers, true);
        if (!TextUtils.isEmpty(accountName)) {
            paramers.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(accountName, 1, null));
        } else {
            HPLog.e("ZZTongActivity", "phone is null! action:" + action);
        }
        paramers.put(CardProtocolKey.CSN_KEY, SecureManager.getInstance().des(csn, 1, null));
        paramers.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        doJsonPost(this, action, SwiperStatusBean.class, paramers);
    }

    public boolean queryMainBankList(boolean isAddCsn) {
        this.showProgressDialog(this, getString(R.string.loading));
        Hashtable<String, String> p = new Hashtable<String, String>();
        p.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        if (isAddCsn) {
            p.put(CardProtocolKey.CSN_KEY, SecureManager.getInstance().des(SwiperUtils.getCsn(), 1, null));
        }
        doJsonPost(this, Do_ZztBankList, BankList.class, p);
        return true;
    }

    public boolean queryBankProvinceFlag(String bankCode) {
        this.showProgressDialog(this, getString(R.string.loading));
        if (TextUtils.isEmpty(bankCode)) {
            onBankProvincesLoad(new ArrayList<BankProvince>(), Do_ZztBankProvinceList);
            return false;
        }
        Hashtable<String, String> p = new Hashtable<String, String>();
        p.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        p.put(UCProtocolKey.KEY_BANKCODE, bankCode);
        p.put("pageSize", pageSize);
        doJsonPost(this, Do_ZztBankProvinceList, BankProvinceList.class, p);
        return true;
    }

    public boolean queryAreaFlag(String bankCode, String text, String provinceId) {
        if (TextUtils.isEmpty(bankCode) || TextUtils.isEmpty(provinceId)) {
            HPLog.i("tag", "bankCode或者provinceId为空");
            // 如果搜索的内容为空，返回空的搜索结果。
            onBankAreaLoad(new ArrayList<BankArea>(), Do_ZztBankAreaList);
            return false;
        }
        Hashtable<String, String> p = new Hashtable<String, String>();
        p.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        p.put("bankCode", String.valueOf(bankCode));
        if (!TextUtils.isEmpty(provinceId)) {
            p.put("provinceId", provinceId);
        }
        p.put("searchText", text);
        p.put("pageSize", PAGESIZE);
        // 查询支行，不显示loading对话框
        doJsonPost(true, this, Do_ZztBankAreaList, BankAreaBean.class, p, false);
        return true;
    }

    public boolean querySubBankList(String bankCode, String text) {
        if (TextUtils.isEmpty(bankCode) || TextUtils.isEmpty(text)) {
            // 如果搜索的内容为空，返回空的搜索结果。
            onBanksLoad(new ArrayList<Bank>(), Do_ZztSubBankList);
            return false;
        }
        Hashtable<String, String> p = new Hashtable<String, String>();
        p.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        p.put("bankCode", String.valueOf(bankCode));
        p.put("searchText", text);
        p.put("pageSize", PAGESIZE);
        // 查询支行，不显示loading对话框
        doJsonPost(true, this, Do_ZztSubBankList, SubBankBean.class, p, false);
        return true;
    }

    public void appendAddresses(Hashtable<String, String> p, boolean isLocation) {
        String lat = BaseProtocolKey.KEY_LATITUDE;
        String loat = BaseProtocolKey.KEY_LONGTITUDE;
        String adds = BaseProtocolKey.KEY_ADDRESS;
        if (ZZTConfig.isTestLocation) {
            lat = BaseProtocolKey.KEY_TEST_LATITUDE;
            loat = BaseProtocolKey.KEY_TEST_LONGTITUDE;
            adds = BaseProtocolKey.KEY_TEST_ADDRESS;
        }
        Double latitude = (Double) ClientEngine.getInstance().getGlobal(lat, 0d);
        Double longtitude = (Double) ClientEngine.getInstance().getGlobal(loat, 0d);
        String add = (String) ClientEngine.getInstance().getGlobal(adds);
        if (0d != latitude && 0d != longtitude && !TextUtils.isEmpty(add)) {
            if (isLocation) {
                p.put(BaseProtocolKey.KEY_LOCATION, latitude.toString() + "," + longtitude.toString());
                p.put(BaseProtocolKey.KEY_ADDRESS, add);
            }
        } else {
            HPLog.e(HPLog.YL_TAG, "no address!");
        }

    }

    public boolean checkExpireDate(String expireDate) {
        try {
            Calendar cal = Calendar.getInstance();// 使用日历类
            int year = cal.get(Calendar.YEAR);// 得到年
            int month = cal.get(Calendar.MONTH) + 1;// 得到月，因为从0开始的，所以要加1
            int mYear = 2000 + Integer.parseInt(expireDate.substring(0, 2));
            int mMonth = Integer.parseInt(expireDate.substring(2));
            HPLog.e(HPLog.FDL_TAG, "year:" + year + "month:" + month + "mYear:" + mYear + "mMonth:" + mMonth);
            if (year <= mYear) {
                if (year == mYear) {
                    if (month > mMonth) {
                        return false;
                    }
                }
                return true;
            }
            return false;
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return false;
        }
    }

    public void finishDialog(String content) {
        try {
            this.showAlertDialog(this, getString(R.string.tip), content, false, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    finish();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            HPLog.e(HPLog.FDL_TAG, "checkExpireDate Error");
        }
    }

	/*
     * (non-Javadoc)
	 * 
	 * @see com.handpay.framework.swiper.ISwiperListener#test()
	 */

    public void onConnectSuccess() {

    }

    public void goToVPos() {
        mLastClickTime = 0L;
    }

    public boolean isVoice(SwiperModel swiperModel) {
        switch (swiperModel) {
            case KOAL_VOICE:
            case GJACK_VOICE_MAG:
            case GJACK_VOICE_IC:
            case BBPOS_VOICE:
            case CMSET_VOICE:
            case NEWLAND_VOICE_IC: {
                return true;
            }
            default:
                return false;
        }
    }

    /***
     * 上传银行卡图片
     *
     * @param fileUrl
     * @param mPlainAccount
     * @param transTime
     * @param transSN
     * @param merchantcode
     * @param imageCardNo
     * @param isAfreshPic
     * @param isshowdialog
     */
    public void upLoadBankCardPic(final String fileUrl, final String mPlainAccount, final String transTime, final String transSN, final String merchantcode, final String imageCardNo, final boolean isAfreshPic, final boolean isshowdialog) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HPLog.e(HPLog.FDL_TAG, "-----upLoadBankCardPics--start----");
                upLoadBankCardPics(fileUrl, mPlainAccount, transTime, transSN, merchantcode, imageCardNo, isAfreshPic, isshowdialog);
            }
        }).start();
    }

    @SuppressLint("NewApi")
    private void upLoadBankCardPics(final String fileUrl, String mPlainAccount, String transTime, String transSN, String merchantcode, String imageCardNo, boolean isAfreshPic, boolean isshowdialog) {
        HPLog.e(HPLog.FDL_TAG, "mPlainAccount=" + mPlainAccount + "transTime=" + transTime + "transSN=" + transSN + "merchantcode=" + merchantcode + "fileUrl=" + fileUrl);
        if (TextUtils.isEmpty(fileUrl)) {
            HPLog.e(HPLog.FDL_TAG, "没有拍照---fileUrl==null---");
            return;
        }
        if (isshowdialog) {
            this.showProgressDialog(this, getString(R.string.pleasewait));
        }
        byte[] imgByte = BitmapZipUtils.getCatBitmap(fileUrl, 480, 800, 200);
//        BitmapUtil.saveByte_File(imgByte);
        if (imgByte == null) {
            HPLog.e(HPLog.FDL_TAG, "没有拍照------");
            return;
        }
        String hex = CommonUtils.bytesToHexString(imgByte);

        String imgCheck = CommonUtils.getCRC(new CRC32(), imgByte);

        Hashtable<String, String> params = new Hashtable<String, String>();

        params.put("cardImage", hex);
        params.put("cardImageCheck", imgCheck);
        if (!TextUtils.isEmpty(imageCardNo)) {
            imageCardNo = imageCardNo.replaceAll(" ", "");
            HPLog.e(HPLog.FDL_TAG, "imageCardNo----" + imageCardNo);
            params.put("imageCardNo", SecureManager.getInstance().des(imageCardNo, 1, null));
        }
        if (isAfreshPic) {
            HPLog.e(HPLog.FDL_TAG, "upLoadBankCardPics----isRepair =1");
            params.put("isRepair", "1");// 重新拍
        } else {
            params.put("isRepair", "0");// 非重拍
        }
        if (!TextUtils.isEmpty(mPlainAccount)) {
            params.put("cardNo", mPlainAccount);
        }
        // 渠道
        params.put(ATProtocolConstant.CHANNEL, ClientEngine.CHANNEL);
        params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
        params.put("transTime", transTime);
        params.put("transSN", SecureManager.getInstance().des(transSN, 1, null));
        params.put("merchantcode", SecureManager.getInstance().des(merchantcode, 1, null));
        HPLog.e(HPLog.FDL_TAG, "Do_ZztPurchaseCardCollectInfo------" + params.toString());
        HPLog.e(HPLog.FDL_TAG, "-----upLoadBankCardPics--Do_ZztPurchaseCardCollectInfo--start--");

//        HttpSFTConnector.doPostCSC(new CoreServiceCallback() {
//            @Override
//            public void callbackNetResponse(String action, Hashtable<String, Object> resp, boolean showAlert, boolean dataCompile) {
//                ZZTongActivity.this.closeProgressDialog();
//                File img=new File(fileUrl);
//                if(img.exists()){
//                    img.delete();
//                    HPLog.e(HPLog.TAG_RESULT, "bank img delete su");
//                }
//            }
//        }, ZZTongActivity.Do_ZztPurchaseCardCollectInfo, params);

        NetEngineListener listener = new NetEngineListener() {

            @Override
            public void callbackNetResponse(String action, Hashtable<String, Object> resp, boolean showAlert, boolean dataCompile) {
                ZZTongActivity.this.closeProgressDialog();
                File img = new File(fileUrl);
                HPLog.i(HPLog.YL_TAG, "bank img :" + fileUrl + " exists:" + img.exists());
                if (img.exists()) {
                    img.delete();
                }
            }

            @Override
            public void callbackJsonNetResponse(String action, ResponseBean resp, boolean showAlert) {
                ZZTongActivity.this.closeProgressDialog();
                File img = new File(fileUrl);
                HPLog.i(HPLog.YL_TAG, "bank img :" + fileUrl + " exists:" + img.exists());
                if (img.exists()) {
                    img.delete();
                }
            }
        };
        HttpSFTConnector.doVolleyJsonPost(listener, ZZTongActivity.Do_ZztPurchaseCardCollectInfo, ResponseBean.class, params, false, 0);
    }

    public static Bitmap doCropImage(byte[] imgBytes) {
        Bitmap btmap = BitmapFactory.decodeStream(new ByteArrayInputStream(imgBytes));
        if (null != btmap) {
            int width = btmap.getWidth();
            int height = btmap.getHeight();
            if (width <= 0) {
                width = screenWidth > 0 ? screenWidth / 2 : 700;
            }
            if (height <= 0) {
                height = screenHeight > 0 ? screenHeight / 4 : 200;
            }
            HPLog.e("TAG", "TAG :width = " + width + "and height = " + height);
            btmap = Bitmap.createScaledBitmap(btmap, width, height, false);
        }
        return btmap;
    }

    public void showTipCamera(boolean isshowdialog) {
        if (isshowdialog) {
            ZZTShowDialog dialog = new ZZTShowDialog(this, R.layout.dialog, R.style.dialog);
            dialog.setDialogCallback(new ZZTShowDialog.Dialogcallback() {
                @Override
                public void ButtonOk() {
                    openCustomCameraActivity();
                }

                @Override
                public void ButtonCancel() {
                    // goTo_Vpos_Activity(null, null);
                }
            });
            dialog.show();
        } else {
            openCustomCameraActivity();
        }
    }

    private void openCustomCameraActivity() {
        if (AndPermission.hasPermission(this, Manifest.permission.CAMERA)) {
            Intent cIntent = new Intent(ZZTongActivity.this, CameraCardPhotoActivity.class);
            ZZTongActivity.this.startActivityForResult(cIntent, ZZTConstant.REQUEST_CAMERA_CODE);
        } else {
            AndPermission.with(this).requestCode(PermissionRequestCode.REQUEST_CODE_PERMISSION_CAMERA).
                    permission(Manifest.permission.CAMERA).
                    rationale(new RationaleListener() {
                        @Override
                        public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                            AndPermission.rationaleDialog(ZZTongActivity.this, rationale).show();
                        }
                    }).send();
        }

    }

//    public void goTo_Vpos_Activity(DialogInterface dialog) {
//        if (dialog != null) {
//            dialog.dismiss();
//        }
//    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        HPLog.i(HPLog.YL_TAG, "onSaveInstanceState:");
        AccountUtils.Account account = ((ZZTApplication) this.getApplicationContext()).getAccount();
        outState.putSerializable(key_saveInstanceState, account);
        super.onSaveInstanceState(outState);

    }


    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        HPLog.i(HPLog.YL_TAG, "onRestoreInstanceState:");
        super.onRestoreInstanceState(savedInstanceState);
        AccountUtils.Account account = (AccountUtils.Account) savedInstanceState.getSerializable(key_saveInstanceState);
        ((ZZTApplication) this.getApplicationContext()).setAccount(account);
    }


    public boolean showNoTranctionMsg() {
        if (!Address.checkAddressIsSuccess()) {
            showAlertDialog(ZZTongActivity.this, getString(R.string.tip), getString(R.string.text_limit_address), true, new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }, null);
            return false;
        }
        return true;
    }
}
